<template>
    <div class="button-container">
        <el-button type="primary" @click="openDialog"> 新增图书 </el-button>
    </div>
    <div class="font-size-controls">
        <el-button @click="increaseFontSize">增大字号 +</el-button>
        <el-button @click="decreaseFontSize">减小字号 -</el-button>
        <el-button @click="resetFontSize">重置字号 reset</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="新增图书" width="300px">
        <el-form ref="form" :model="form" label-position="right" label-width="100px" :rules="rules">
            <el-form-item label="书名" prop="bookname">
                <el-input v-model="form.bookname" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
                <el-input v-model="form.author" />
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
                <el-input v-model="form.publisher" />
            </el-form-item>
            <el-form-item label="类别" prop="category">
                <el-input v-model="form.category" />
            </el-form-item>
            <el-form-item label="定价" prop="price">
                <el-input v-model="form.price" type="number" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
        </template>
    </el-dialog>

    <el-table :data="books" style="width: 100%" :row-class-name="getCategoryCellClass">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="书名" width="120" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="isbn" label="ISBN" width="120" />
        <el-table-column prop="publisher" label="出版社" width="120" />
        <el-table-column prop="publishDate" label="出版日期" width="120" />
        <el-table-column prop="price" label="定价" width="120"/>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="createdAt" label="创建时间" width="220" />
        <el-table-column prop="updatedAt" label="更新时间" width="220" />
        <el-table-column label="类别" width="120">
            <template #default="scope">
                <span :class="getCategoryClass(scope.row.category)">{{ scope.row.category }}</span>
            </template>
        </el-table-column>
        <el-table-column label="选项操作" min-width="100">
            <template #default="scope">
                <el-button link type="danger" size="small" @click.prevent="handleDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <div class="pagination-container">
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
            :total="books ? books.length : 0" layout="prev, pager, next" style="margin-top: 20px"
            v-if="books && books.length > 0" />
        <div v-else style="text-align: center; margin-top: 20px">暂无数据</div>
    </div>

    <!-- 统计信息显示区域 -->
    <div class="stats-container" v-if="books && books.length > 0">
        <h3>图书统计信息</h3>
        <p>图书总数: {{ bookStats.totalBooks }}，平均价格: {{ bookStats.averagePrice.toFixed(2) }} 元</p>
        <p>分类统计:</p>
        <ul>
            <li v-for="(count, category) in bookStats.categoryCounts" :key="category">
                {{ category }}: {{ count }} 本
            </li>
        </ul>
    </div>
</template>
<script>
import axios from 'axios';
import { onMounted } from 'vue';
export default {

    data() {
        return {
            dialogFormVisible: false,
            paginatedBooks: [],
            currentPage: 1,
            pageSize: 10,
            books: [],
            form: {
                bookname: '',
                author: '',
                publisher: '',
                category: '',
            },
            rules: {
                bookname: [{ required: true, message: '请输入书名', trigger: 'blur' }],
                author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
                publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
                category:[{required:true,message:"输入类别",trigger:"blur"}],
            price:[{required:true,message:"输入定价",trigger:"blur"}]

            },
        };
    },
    methods: {
        openDialog() {
            this.dialogFormVisible = true;
        },
        handleDelete(id) {
            this.$confirm('确认删除该图书吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                this.books = this.books.filter(book => book.id !== id);
                this.updatePaginatedBooks();
                this.$message.success('删除成功');
            }).catch((error) => {
                if (error === 'cancel') {
                    this.$message.info('已取消删除');
                } else {
                    this.$message.error(`删除失败: ${error.message || '未知错误'}`);
                }
            });

    },
    generateUniqueId() {
        return Date.now().toString(36) + Math.random().toString(36).substring(2);
    },
    tableRowClassName({ row }) {
        return '';
    },
    increaseFontSize() {
        const table = document.querySelector('.el-table');
        if (table) {
            const currentSize = parseFloat(window.getComputedStyle(table).fontSize) || 14;
            table.style.fontSize = `${currentSize + 1}px`;
        }
    },
    decreaseFontSize() {
        const table = document.querySelector('.el-table');
        if (table) {
            const currentSize = parseFloat(window.getComputedStyle(table).fontSize) || 14;
            table.style.fontSize = `${Math.max(currentSize - 1, 10)}px`;
        }
    },
    resetFontSize() {
        const table = document.querySelector('.el-table');
        if (table) {
            table.style.fontSize = '14px';
        }
    },
    mounted() {
        axios.get('/data/books.json')
            .then(response => {
                this.books = response.data;
                console.log('数据获取成功:', response.data);
                this.updatePaginatedBooks();
            })
            .catch(error => {
                console.error('获取图书数据失败:', error);
                console.error('请求URL:', error.config.url);
                console.error('响应状态:', error.response?.status);
                console.error('响应数据:', error.response?.data);
            });
    },
    getCategoryCellClass({ row }) {
        if (row.category === '文学') {
            return 'literature-cell';
        } else if (row.category === '科技') {
            return 'technology-cell';
        } else if (row.category === '历史') {
            return 'history-cell';
        }
        return '';
    },
    getCategoryClass(category) {
        const categoryClasses = {
            '文学': 'category-literature',
            '科技': 'category-technology', 
            '历史': 'category-history',
            '艺术': 'category-art',
            '哲学': 'category-philosophy',
            '经济': 'category-economics',
            '教育': 'category-education',
            '医学': 'category-medicine'
        };
        return categoryClasses[category] || 'category-default';
    },
    submitForm() {
        this.$refs.form.validate((valid) => {
            if (valid) {
                const newBook = {
                    id: this.generateUniqueId(),
                    title: this.form.bookname,
                    category: this.form.category,
                    author: this.form.author,
                    isbn: this.form.isbn || '',
                    publisher: this.form.publisher,
                    publishDate: this.form.publishDate || '',
                    price: this.form.price,
                    stock: this.form.stock || 0,
                    createdAt: new Date().toLocaleString(),
                    updatedAt: new Date().toLocaleString(),
                };
                console.log('提交的图书信息:', JSON.stringify(newBook, null, 2));
                this.books.push(newBook);
                this.$message.success('图书添加成功！');
                this.dialogFormVisible = false;
                this.form = {
                    bookname: '',
                    author: '',
                    publisher: '',
                    price: '',
                };
                this.$nextTick(() => {
                    this.$forceUpdate();
                    this.updatePaginatedBooks();
                });
            }
        });
    },
    handleCurrentChange(page) {
        this.currentPage = page;
        this.updatePaginatedBooks();
    },
    updatePaginatedBooks() {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        this.paginatedBooks = this.books.slice(start, end);
    },
},
mounted() {
    this.updatePaginatedBooks();
},
computed: {
    bookStats() {
        const stats = {
            totalBooks: this.books.length,
            categoryCounts: {},
            averagePrice: 0,
        };

        // 统计每种分类的数量
        this.books.forEach(book => {
            if (book.category) {
                stats.categoryCounts[book.category] = (stats.categoryCounts[book.category] || 0) + 1;
            }
        });

        // 计算平均价格
        if (this.books.length > 0) {
            const totalPrice = this.books.reduce((sum, book) => sum + (parseFloat(book.price) || 0), 0);
            stats.averagePrice = totalPrice / this.books.length;
        }

        return stats;
    },
},
};
</script>
<style scoped>
.button-container {
    margin: 20px 0;
    padding-left: 10px;
    font-size: 30px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 5px;
}

.literature-cell {
    color: blue;
}

.technology-cell {
    color: yellow;
}

.history-cell {
    background-color: red;
}

.font-size-controls {
    margin: 10px 0;
    padding-left: 10px;
}

.stats-container {
    margin: 20px 10px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
}

.stats-container h3 {
    margin-top: 0;
    color: #303133;
    font-size: 18px;
    margin-bottom: 15px;
}

.stats-container p {
    margin: 8px 0;
    color: #606266;
    font-size: 14px;
}

.stats-container ul {
    margin: 10px 0;
    padding-left: 20px;
}

.stats-container li {
    margin: 5px 0;
    color: #606266;
    font-size: 14px;
}

/* 分类标签样式 */
.category-literature {
    background-color: #e8f4fd;
    color: #1890ff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-technology {
    background-color: #f6ffed;
    color: #52c41a;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-history {
    background-color: #fff2e8;
    color: #fa8c16;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-art {
    background-color: #f9f0ff;
    color: #722ed1;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-philosophy {
    background-color: #fff1f0;
    color: #f5222d;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-economics {
    background-color: #e6fffb;
    color: #13c2c2;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-education {
    background-color: #feffe6;
    color: #a0d911;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-medicine {
    background-color: #fff0f6;
    color: #eb2f96;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.category-default {
    background-color: #f5f5f5;
    color: #666666;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}
</style>